package com.yuexin.project.dailymenu.everyday.service;

import com.yuexin.common.support.Convert;
import com.yuexin.common.utils.StringUtils;
import com.yuexin.common.utils.security.ShiroUtils;
import com.yuexin.framework.aspectj.lang.annotation.Excel;
import com.yuexin.project.dailymenu.dishlist.domain.DishList;
import com.yuexin.project.dailymenu.dishlist.mapper.DishListMapper;
import com.yuexin.project.dailymenu.dishtype.domain.DishType;
import com.yuexin.project.dailymenu.dishtype.mapper.TypeMapper;
import com.yuexin.project.dailymenu.everyday.domain.DailyMenuDish;
import com.yuexin.project.dailymenu.everyday.domain.EverydayMenu;
import com.yuexin.project.dailymenu.everyday.domain.TWeekDishLog;
import com.yuexin.project.dailymenu.everyday.export.*;
import com.yuexin.project.dailymenu.everyday.mapper.EveryDayMenuDishMapper;
import com.yuexin.project.dailymenu.everyday.mapper.EverydayMenuMapper;
import com.yuexin.project.dailymenu.everyday.mapper.TWeekDishLogMapper;
import com.yuexin.project.dailymenu.menumanager.domain.Manager;
import com.yuexin.project.dailymenu.menumanager.domain.MenuDish;
import com.yuexin.project.dailymenu.menumanager.mapper.ManagerMapper;
import com.yuexin.project.dailymenu.menumanager.mapper.MenuDishMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 每日菜单 服务层实现
 * 
 * @author yuexin
 * @date 2018-10-14
 */
@Service
public class EverydayMenuServiceImpl implements IEverydayMenuService {
	@Autowired
	private EverydayMenuMapper everydayMenuMapper;

	@Autowired
	private EveryDayMenuDishMapper everydayMenuDishMapper;

	@Autowired
	private MenuDishMapper menuDishMapper;

	@Autowired
	private ManagerMapper managerMapper;

	@Autowired
	private TypeMapper typeMapper;

    @Autowired
    private DishListMapper dishListMapper;



	@Autowired
	private TWeekDishLogMapper  tWeekDishLogMapper;

    /**
	 * 查询每日菜单信息
	 *
	 * @param dailyId 每日菜单ID
	 * @return 每日菜单信息
	 */
	@Override
	public EverydayMenu selectEverydayMenuById(Integer dailyId) {
		return everydayMenuMapper.selectEverydayMenuById(dailyId);
	}

	/**
	 * 根据日期获得星期
	 * @param date
	 * @return
	 *//*
    private String getWeekOfDate(Date date) {
	    String[] weekDaysName = { "周日", "周一", "周二", "周三", "周四", "周五", "周六" };
	    //String[] weekDaysCode = { "0", "1", "2", "3", "4", "5", "6" };
	    Calendar calendar = Calendar.getInstance();
	    calendar.setTime(date);
	    int intWeek = calendar.get(Calendar.DAY_OF_WEEK) - 1;
	    return weekDaysName[intWeek];
    } */

	/**
	 * 查询每日菜单列表
	 *
	 * @param everydayMenu 每日菜单信息
	 * @return 每日菜单集合
	 */
	@Override
	public List<EverydayMenu> selectEverydayMenuList(EverydayMenu everydayMenu) {

		return everydayMenuMapper.selectEverydayMenuList(everydayMenu);
	}

	/**
	 * 新增每日菜单
	 *
	 * @param everydayMenu 每日菜单信息
	 * @return 结果
	 */
	@Override
	public int insertEverydayMenu(EverydayMenu everydayMenu) {
//		if(everydayMenu.getMenuId() == null || "".equals(everydayMenu.getMenuId())){
		return everydayMenuMapper.insertEverydayMenu(everydayMenu);
//		}else{
			/*Manager manager = managerMapper.selectManagerById(everydayMenu.getMenuId());
			everydayMenu.setIsBreakFast(manager.getIsBreakFast());
			everydayMenu.setIsLunch(manager.getIsLunch());
			everydayMenu.setIsDinner(manager.getIsDinner());
			everydayMenuMapper.insertEverydayMenu(everydayMenu);
			
	        // 删除菜单与菜品关联 全部
			everydayMenu.setDinnerType(null);
	    	everydayMenuDishMapper.deleteEverydayMenuDishByMenuId(everydayMenu);
	        
	    	// 新增菜单与菜品关联
	    	EverydayMenu every = everydayMenuMapper.selectEverydayByMenuId(everydayMenu.getMenuId());
	    	List<MenuDish> menuDishs = menuDishMapper.selectMenuDishList(everydayMenu.getMenuId());
	    	return insertDailyEverydayMenuDish(menuDishs,every.getDailyId());*/
		//}
	}

	/**
	 * 新增菜单菜品
	 *
	 * @param
	 */
	public int insertDailyEverydayMenuDish(List<MenuDish> menuDishs, Integer dailyId) {
		int rows = 1;
		List<DailyMenuDish> list = new ArrayList<DailyMenuDish>();
		for (MenuDish menuDish : menuDishs) {
			DailyMenuDish rd = new DailyMenuDish();
			rd.setDailyId(dailyId);
			rd.setDishId(menuDish.getDishId());
			rd.setDinnerType(menuDish.getDinnerType());
			rd.setCompanyId(ShiroUtils.getCompanyId());
			list.add(rd);
		}

		if (list.size() > 0) {
			rows = everydayMenuDishMapper.batchEverydayMenuDish(list);
		}
		return rows;
	}

	/**
	 * 修改每日菜单
	 *
	 * @param everydayMenu 每日菜单信息
	 * @return 结果
	 */
	@Override
	public int updateEverydayMenu(EverydayMenu everydayMenu) {
		Manager manager = managerMapper.selectManagerById(everydayMenu.getMenuId());
		if (manager != null) {
			everydayMenu.setIsBreakFast(manager.getIsBreakFast());
			everydayMenu.setIsLunch(manager.getIsLunch());
			everydayMenu.setIsDinner(manager.getIsDinner());
			everydayMenu.setIsOther(manager.getIsOther());
		}
		int menuNum = everydayMenuMapper.updateEverydayMenu(everydayMenu);
		// 删除菜单与菜品关联 全部
		everydayMenu.setDinnerType(null);
		everydayMenuDishMapper.deleteEverydayMenuDishByMenuId(everydayMenu);
		// 新增菜单与菜品关联
		List<MenuDish> menuDishs = menuDishMapper.selectMenuDishList(everydayMenu);
		//不开餐不插入菜单菜品表
		if ("0".equals(everydayMenu.getIsOpen())) {
			return menuNum;
		}

		return insertDailyEverydayMenuDish(menuDishs, everydayMenu.getDailyId());
	}

	/**
	 * 删除每日菜单对象
	 *
	 * @param ids 需要删除的数据ID
	 * @return 结果
	 */
	@Override
	public int deleteEverydayMenuByIds(String ids) {
		return everydayMenuMapper.deleteEverydayMenuByIds(Convert.toStrArray(ids));
	}

	/**
	 * 新增菜单菜品
	 *
	 * @param
	 */
	public int insertEverydayMenuDish(EverydayMenu everydayMenu) {
		int rows = 1;
		List<DailyMenuDish> list = new ArrayList<DailyMenuDish>();
		for (Integer dish : everydayMenu.getDishIds()) {
			DailyMenuDish rd = new DailyMenuDish();
			rd.setDailyId(everydayMenu.getDailyId());
			rd.setDishId(dish);
			rd.setDinnerType(everydayMenu.getDinnerType());
			rd.setCompanyId(ShiroUtils.getCompanyId());
			list.add(rd);
		}
		if (list.size() > 0) {
			rows = everydayMenuDishMapper.batchEverydayMenuDish(list);
		}
		return rows;
	}

	/**
	 * 修改菜品信息
	 *
	 * @param
	 * @return 结果
	 */
	@Override
	public int updateRule(EverydayMenu everydayMenu) {

		String dinnerType = everydayMenu.getDinnerType();
		String isOpen = everydayMenu.getIsOpen();
		if ("0".equals(dinnerType)) {
			everydayMenu.setIsBreakFast(isOpen);
		} else if ("1".equals(dinnerType)) {
			everydayMenu.setIsLunch(isOpen);
		} else if ("2".equals(dinnerType)) {
			everydayMenu.setIsDinner(isOpen);
		} else if ("3".equals(dinnerType)) {
			everydayMenu.setIsOther(isOpen);
		}
		everydayMenuMapper.updateEverydayMenu(everydayMenu);
		// 删除菜单与菜品关联
		everydayMenuDishMapper.deleteEverydayMenuDishByMenuId(everydayMenu);
		//managerMapper.deleteManagerById(manager.getMenuId());
		// 新增菜单与菜品关联
		return insertEverydayMenuDish(everydayMenu);
	}


	/**
	 * @param date
	 * @param num
	 * @return
	 * @throws ParseException
	 */
	public static String plusDay(Date date, int num) throws ParseException {
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");

		Calendar ca = Calendar.getInstance();
		ca.setTime(date);
		ca.add(Calendar.DATE, num);
		Date currDate = ca.getTime();
		String endDate = format.format(currDate);
		return endDate;
	}

	public List<ExportDayItem> getExportMenuList(String strStartDay, String strEndDay, String companyId,String dinnerType) {
		List<ExportDayItem> exportDayItemList = new ArrayList<>();
		try {
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			Date startDay = sdf.parse(strStartDay);
			Date endDay = sdf.parse(strEndDay);
			long days = (endDay.getTime() - startDay.getTime()) / (24 * 60 * 60 * 1000);
			List<DishType> dishTypeList = typeMapper.selectDishTypeAll(companyId);

			for (int i = 0; i <= days; i++) {
				ExportDayItem exportDayItem = new ExportDayItem();
				String day = plusDay(startDay, i);
				exportDayItem.setDay(day);
				exportDayItem.setWeek(ExcelReader.getWeekOfDate(day));
				exportDayItem.setMenuItemList(new ArrayList<>());

				for (DishType dishType : dishTypeList) {
					String belongType = dishType.getBelongType();
					if (belongType!=null && belongType.indexOf("," + dinnerType + ",") != -1) {
						int nums = dishType.getTypeNums();
						if (nums > 0) {
							ExportMenuItem e = new ExportMenuItem();
							e.setType(dishType.getTypeName());
							e.setTypeList(new ArrayList<>());
							for (int j = 0; j < nums; j++) {
								e.getTypeList().add("");
							}
							exportDayItem.getMenuItemList().add(e);
						}
					}
				}
				exportDayItemList.add(exportDayItem);
			}


		} catch (Exception e) {
			e.printStackTrace();
		}
		return exportDayItemList;
	}

	@Override
	public ExportErrorResult exportExcel(String excelPath, String companyId, String dinnerType, int replaceIt) {
		List<ExportError> exportErrors = new ArrayList<>();
		ExportErrorResult result = new ExportErrorResult();
		result.setErrorList(exportErrors);
		List<ExportDayItem> exportDayItemList = ExcelReader.parse(ExcelReader.readExcel(excelPath));
		int startLines = 3;

		List<DishType> dishTypeList = typeMapper.selectDishTypeAll(companyId);
		List<DishList> dishList = dishListMapper.selectDishListAll(companyId);

		for (ExportDayItem exportDayItem : exportDayItemList) {
			int curLines = 0;
			List<ExportMenuItem> exportMenuItems = exportDayItem.getMenuItemList();
			for (ExportMenuItem exportMenuItem : exportMenuItems) {
				String type = exportMenuItem.getType();
				int typeNums = exportMenuItem.getTypeList().size();
				curLines += typeNums;
				DishType existDish = hasDishType(dishTypeList, type);
				if(existDish!=null && existDish.getBelongType()==null) {
					existDish.setBelongType("");
				}
				if (replaceIt == 0) {
					if (existDish == null) {
						ExportError e = new ExportError();
						e.setErrorMsg(type + " 菜品类型不存在！");
						e.setLine(String.valueOf(curLines + startLines));
						exportErrors.add(e);
						result.setErrorList(exportErrors);
						return result;
					}else{

						if (existDish.getBelongType().indexOf("," + dinnerType + ",") == -1) {
							existDish.setBelongType(existDish.getBelongType() + "" + dinnerType + ",");
							typeMapper.updateType(existDish);
						}
					}

					List<String> dishNameList = exportMenuItem.getTypeList();
					if (dishNameList != null) {

						for (String dishName : dishNameList) {
							if (!StringUtils.isEmpty(dishName)) {
								DishList existDishList = hasDish(dishList, dishName);
								if (existDishList == null) {
									ExportError e = new ExportError();
									e.setErrorMsg(dishName + " 菜品不存在！");
									e.setLine(String.valueOf(curLines + startLines));
									exportErrors.add(e);
									result.setErrorList(exportErrors);
									return result;
								}
							}
						}

					}

				} else {
					if (existDish == null) {
						existDish = new DishType();
						existDish.setTypeName(type);
						existDish.setTypeNums(typeNums);
						existDish.setTypeSort(1);
						existDish.setStatus("0");
						existDish.setBelongType("," + dinnerType + ",");
						existDish.setCompanyId(companyId);

						typeMapper.insertType(existDish);
						dishTypeList.add(existDish);
					} else {

						if (existDish.getBelongType().indexOf("," + dinnerType + ",") == -1) {
							existDish.setBelongType(existDish.getBelongType() + "" + dinnerType + ",");
							typeMapper.updateType(existDish);
						}
					}

					List<String> dishNameList = exportMenuItem.getTypeList();
					if (dishNameList != null) {
						for (String dishName : dishNameList) {
							if (!StringUtils.isEmpty(dishName)) {
								DishList existDishList = hasDish(dishList, dishName);
								if (existDishList == null) {
									existDishList = new DishList();
									existDishList.setDishName(dishName);
									existDishList.setStatus("1");
									existDishList.setCompanyId(companyId);
									existDishList.setTypeId(existDish.getTypeId());
									existDishList.setDishSort(0);
									existDishList.setDishPrice(new BigDecimal(0));
									dishListMapper.insertList(existDishList);
									dishList.add(existDishList);
								}
							}
						}
					}//
				}
			}
		}


		for (ExportDayItem exportDayItem : exportDayItemList) {

			String day = exportDayItem.getDay();
			EverydayMenu everydayMenu = new EverydayMenu();
			everydayMenu.setCompanyId(companyId);
			everydayMenu.setDailyDate(ExcelReader.parseDay(day));
			EverydayMenu existMenu = everydayMenuMapper.selectEverydayMenuByDailyDate(everydayMenu);
			if (existMenu == null) {
				existMenu = new EverydayMenu();
				existMenu.setCompanyId(companyId);
				existMenu.setDailyDate(ExcelReader.parseDay(day));
				if (dinnerType.equals("0")) {
					existMenu.setIsBreakFast("1");
					existMenu.setIsOpen("1");

				} else if (dinnerType.equals("1")) {
					existMenu.setIsLunch("1");
					existMenu.setIsOpen("1");
				} else if (dinnerType.equals("2")) {

					existMenu.setIsDinner("1");
					existMenu.setIsOpen("1");
				} else if (dinnerType.equals("3")) {

					existMenu.setIsOther("1");
					existMenu.setIsOpen("1");
				}
				everydayMenuMapper.insertEverydayMenu(existMenu);
			}

			EverydayMenu delDayMenu = new EverydayMenu();
			delDayMenu.setDailyId(existMenu.getDailyId());
			delDayMenu.setDinnerType(dinnerType);
			everydayMenuDishMapper.deleteEverydayMenuDishByMenuId(delDayMenu);
			List<ExportMenuItem> exportMenuItems = exportDayItem.getMenuItemList();

			for (ExportMenuItem exportMenuItem : exportMenuItems) {
				String type = exportMenuItem.getType();

				List<String> dishNameList = exportMenuItem.getTypeList();
				if (dishNameList != null) {
					List<DailyMenuDish> menuDishList = new ArrayList<>();
					for (String dishName : dishNameList) {
						if (!StringUtils.isEmpty(dishName)) {
							DishList existDishList = hasDish(dishList, dishName);
							DailyMenuDish dailyMenuDish = new DailyMenuDish();
							dailyMenuDish.setDinnerType(dinnerType);
							dailyMenuDish.setDishId(existDishList.getDishId());
							dailyMenuDish.setDailyId(existMenu.getDailyId());
							dailyMenuDish.setCompanyId(companyId);

							List<DailyMenuDish> allDishMenuList = everydayMenuDishMapper.selectEverydayMenuDishListByDailyId(existMenu.getDailyId());
							if (!existDishMenu(allDishMenuList, existDishList.getDishId(), dinnerType)) {
								menuDishList.add(dailyMenuDish);
							}

						}
					}
					if (menuDishList.size() > 0) {
						everydayMenuDishMapper.batchEverydayMenuDish(menuDishList);
					}

				}
			}
		}

		//add log

		for (ExportDayItem exportDayItem : exportDayItemList) {
			StringJoiner joiner = new StringJoiner(",");
			List<String> allDishLog = new ArrayList<>();
			String day = exportDayItem.getDay();
			List<ExportMenuItem> exportMenuItemList = exportDayItem.getMenuItemList();
			if (exportMenuItemList != null) {
				exportMenuItemList.stream().forEach(item -> {
					List<String> typeList = item.getTypeList();
					if (typeList != null) {
						typeList.stream().forEach(dishItem -> {
							if (!allDishLog.contains(dishItem)) {
								allDishLog.add(dishItem);
								joiner.add(dishItem);
							}
						});
					}
				});
			}


			int weekOfYear = ExcelReader.getWeekOfYear(day);
			int year = ExcelReader.getYear(day);
			Date startDay = ExcelReader.parseDay(day);
			TWeekDishLog weekDishLog = new TWeekDishLog();
			weekDishLog.setCompanyId(companyId);
			weekDishLog.setDishType(dinnerType);
			weekDishLog.setStartDay(startDay.getTime());
			weekDishLog.setEndDay(startDay.getTime());
			weekDishLog.setIfPublish("1");
			weekDishLog.setMeansDetails(joiner.toString());
			weekDishLog.setWeek(weekOfYear);
			weekDishLog.setYear(year);

			TWeekDishLog dishLog=new TWeekDishLog();

			dishLog.setCompanyId(companyId);
			dishLog.setDishType(dinnerType);
			dishLog.setStartDay(startDay.getTime());
			dishLog.setEndDay(startDay.getTime());
			dishLog.setWeek(weekOfYear);
			dishLog.setYear(year);
			List<TWeekDishLog > oldDishLog= tWeekDishLogMapper.selectTWeekDishLogList(dishLog);
			if(oldDishLog!=null) {
				oldDishLog.stream().forEach( dishLogItem->{
					tWeekDishLogMapper.deleteTWeekDishLogById(dishLogItem.getId());
				});
			}

			tWeekDishLogMapper.insertTWeekDishLog(weekDishLog);

		}


		return result;
	}


	/**

	 * @return
	 */

	private  boolean existDishMenu(List<DailyMenuDish> allDishMenuList  , int dishId,String dinnerType )  {
		for (DailyMenuDish  dailyMenuDish : allDishMenuList) {
			if ( dailyMenuDish.getDinnerType().equals(dinnerType) &&
					dailyMenuDish.getDishId()==dishId

			) {
				return true;
			}
		}
		return false;

	}



	private  DishType hasDishType(List<DishType> dishTypeList  , String type) {
		for (DishType dishType : dishTypeList) {
			if (!StringUtils.isEmpty(type) && dishType.getTypeName().equals(type)) {
				return dishType;
			}
		}
		return null;

	}


    private  DishList hasDish(List<DishList> dishTypeList  , String dishName) {
        for (DishList dishList : dishTypeList) {
            if (!StringUtils.isEmpty(dishName) && dishList.getDishName().equals(dishName)) {
                return dishList;
            }
        }
        return null;

    }



}
